package thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//CountDownLatch的使用
public class Demo43 {
    public static void main(String[] args) throws InterruptedException {
        //10表示任务的个数是10个
        CountDownLatch latch = new CountDownLatch(10);
        //创建一个有4个线程的线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(4);
        for (int i = 1; i <= 10; i++) {
            int id = i;
            threadPool.submit(() -> {
                System.out.println("开始执行子任务："+id);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("子任务执行结束："+id);
                //每次执行完一个任务，countDown减少一个
                latch.countDown();//这段代码必须要放在线程要处理的任务中
            });
        }
        latch.await();
        System.out.println("所有子任务执行完毕");
    }
}
